<template>
  <div class="echart-container">
    <h2>员工概况</h2>

    <!-- 统计卡片区域 -->
    <div class="stats-grid" :class="{ 'keleton-loading': loading }">
      <div
          class="stat-card"
          v-for="card in statCards"
          :key="card.key"
          :style="{ backgroundColor: card.bgColor + '20' }"
      >
        <div class="stat-card-header">{{ card.title }}</div>
        <div class="stat-card-body">
          <span class="stat-card-count">{{ card.count }}</span>
          <span class="stat-card-icon">{{ card.icon }}</span>
        </div>
      </div>
    </div>

    <!-- 第一行图表：员工状态、年龄、性别（前三个） -->
    <div class="charts-row">
      <!-- 员工状态分布图表（第一个） -->
      <div ref="chartRef" class="chart" style="flex-basis: calc(33.33% - 15px);"></div>

      <!-- 年龄分布图表（第二个） -->
      <div ref="ageChartRef" class="chart" style="flex-basis: calc(33.33% - 15px);"></div>

      <!-- 性别分布图表（第三个） -->
      <div ref="genderChartRef" class="chart" style="flex-basis: calc(33.33% - 15px);"></div>
    </div>

    <!-- 第二行图表：用工状态图表（第四个，位于第一个图表下方） -->
    <div class="charts-row">
      <div ref="employmentTypeChartRef" class="chart" style="flex-basis: calc(33.33% - 15px);"></div>

      <!-- 新增：学历分布图表（第五个，与第四个并排） -->
      <div ref="educationChartRef" class="chart" style="flex-basis: calc(33.33% - 15px);"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { listEmployee } from "@/api/employee/dataStatistics/dataStatistics";
import { listExperienceByEducation } from "@/api/experience/experience";
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';

const chartRef = ref(null);
const ageChartRef = ref(null);
const genderChartRef = ref(null);
const employmentTypeChartRef = ref(null);
const educationChartRef = ref(null);
let myChart = null;
let ageChart = null;
let genderChart = null;
let employmentTypeChart = null;
let educationChart = null;
const loading = ref(true);

// 定义统计卡片数据结构
const statCards = reactive([
  { key: 'totalOnJob', title: '在职员工（合计）', count: 0, icon: '🏢', bgColor: '#2f96b4' },
  { key: 'probation', title: '试用期员工', count: 0, icon: '⏳', bgColor: '#1cc88a' },
  { key: 'formal', title: '在职员工', count: 0, icon: '👨‍💼', bgColor: '#4e73df' },
  { key:'retired', title: '退休员工', count: 0, icon: '📥', bgColor: '#36b9cc' },
  { key: 'leave', title: '离职员工', count: 0, icon: '📤', bgColor: '#e74a3b' }
]);

// 学历类型
const educationTypes = ['专科', '本科', '硕士', '博士'];

onMounted(() => {
  // 初始化员工状态图表
  myChart = echarts.init(chartRef.value);
  const employeeStatusOption = {
    title: {
      text: '员工状态分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient:'vertical',
      left: 'left'
    },
    series: [
      {
        name: '员工状态',
        type: 'pie',
        radius: [20, 140],
        roseType: 'area',
        itemStyle: {
          borderRadius: 10
        },
        data: [
          { value: 0, name: '试用期', itemStyle: { color: '#5470c6' } },
          { value: 0, name: '正式员工', itemStyle: { color: '#91cc75' } },
          { value: 0, name: '离职', itemStyle: { color: '#fac858' } },
          { value: 0, name: '退休', itemStyle: { color: '#ee6666' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  myChart.setOption(employeeStatusOption);

  // 初始化年龄分布图表
  ageChart = echarts.init(ageChartRef.value);
  const ageDistributionOption = {
    title: {
      text: '员工年龄分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type:'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['18岁以下', '18-30岁', '31-45岁', '46-60岁', '60以上']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '员工数量',
        type: 'bar',
        data: [0, 0, 0, 0, 0],
        itemStyle: {
          color: '#4e73df'
        }
      }
    ]
  };
  ageChart.setOption(ageDistributionOption);

  // 初始化性别分布图表
  genderChart = echarts.init(genderChartRef.value);
  const genderDistributionOption = {
    title: {
      text: '员工性别分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient:'vertical',
      left: 'left'
    },
    series: [
      {
        name: '性别',
        type: 'pie',
        radius: [20, 140],
        roseType: 'area',
        itemStyle: {
          borderRadius: 10
        },
        avoidLabelOverlap: false,
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { value: 0, name: '男', itemStyle: { color: '#5470c6' } },
          { value: 0, name: '女', itemStyle: { color: '#ee6666' } }
        ]
      }
    ]
  };
  genderChart.setOption(genderDistributionOption);

  // 初始化用工状态图表
  employmentTypeChart = echarts.init(employmentTypeChartRef.value);
  const employmentTypeOption = {
    title: {
      text: '员工用工状态分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}人 ({d}%)'
    },
    legend: {
      orient:'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用工状态',
        type: 'pie',
        radius: [20, 140],
        roseType: 'area',
        itemStyle: {
          borderRadius: 10
        },
        data: [
          { value: 0, name: '全职', itemStyle: { color: '#4e73df' } },
          { value: 0, name: '兼职', itemStyle: { color: '#1cc88a' } }
        ]
      }
    ]
  };
  employmentTypeChart.setOption(employmentTypeOption);

  // 初始化学历分布图表
  educationChart = echarts.init(educationChartRef.value);
  const educationOption = {
    title: {
      text: '员工学历分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}人 ({d}%)'
    },
    legend: {
      orient:'vertical',
      left: 'left'
    },
    series: [
      {
        name: '学历',
        type: 'pie',
        radius: [20, 140],
        roseType: 'area',
        itemStyle: {
          borderRadius: 10
        },
        data: [
          { value: 0, name: '专科', itemStyle: { color: '#5470c6' } },
          { value: 0, name: '本科', itemStyle: { color: '#91cc75' } },
          { value: 0, name: '硕士', itemStyle: { color: '#fac858' } },
          { value: 0, name: '博士', itemStyle: { color: '#ee6666' } }
        ]
      }
    ]
  };
  educationChart.setOption(educationOption);

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart?.resize();
    ageChart?.resize();
    genderChart?.resize();
    employmentTypeChart?.resize();
    educationChart?.resize();
  });

  // 立即请求数据
  fetchData();
});

const fetchData = async () => {
  try {
    loading.value = true;
    const response = await listEmployee();
    const data = response.data;
    const experienceResponse = await listExperienceByEducation();
    const experienceData = experienceResponse.data;
    console.log('接口返回的原始数据:', data);

    // 更新员工状态图表数据
    if (myChart && data) {
      myChart.setOption({
        series: [{
          data: [
            { value: data.probation || 0, name: '试用期' },
            { value: data.formal || 0, name: '正式员工' },
            { value: data.leave || 0, name: '离职' },
            { value: data.retired || 0, name: '退休' }
          ]
        }]
      });
    }

    // 更新年龄分布图表数据
    if (ageChart && data) {
      ageChart.setOption({
        series: [{
          data: [
            data.under18 || 0,
            data.between18And30 || 0,
            data.between31And45 || 0,
            data.between46And60 || 0,
            data.over60 || 0
          ]
        }]
      });
    }

    // 更新性别分布图表数据
    if (genderChart && data) {
      genderChart.setOption({
        series: [{
          data: [
            { value: data.male || 0, name: '男' },
            { value: data.female || 0, name: '女' }
          ]
        }]
      });
    }

    // 更新用工状态图表数据
    if (employmentTypeChart && data) {
      employmentTypeChart.setOption({
        series: [{
          data: [
            { value: data.fullTime || 0, name: '全职' },
            { value: data.partTime || 0, name: '兼职' },
            { value: data.other || 0, name: '其他' }
          ]
        }]
      });
    }

    // 更新学历分布图表数据
    if (educationChart && experienceData) {
      educationChart.setOption({
        series: [{
          data: [
            { value: experienceData.juniorCollegeNumber || 0, name: '专科' },
            { value: experienceData.bachelorNumber || 0, name: '本科' },
            { value: experienceData.masterNumber || 0, name: '硕士' },
            { value: experienceData.doctorNumber || 0, name: '博士' }
          ]
        }]
      });
    }

    // 更新卡片数据
    statCards.forEach(card => {
      if (card.key === 'totalOnJob') {
        card.count = parseInt(data.probation || 0) + parseInt(data.formal || 0);
      } else if (data[card.key]!== undefined) {
        card.count = parseInt(data[card.key]);
      }
    });
  } catch (error) {
    ElMessage.error('获取员工数据失败');
    console.error('获取员工数据失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.echart-container {
  width: 100%;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card-header {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 10px;
}

.stat-card-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-card-count {
  font-size: 28px;
  font-weight: bold;
  color: #343a40;
}

.stat-card-icon {
  font-size: 36px;
}

/* 图表行样式 */
.charts-row {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  min-height: 350px;
}

/* 第二个图表行调整：使第四个和第五个图表并排 */
.charts-row:nth-child(2) {
  margin-top: -20px;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .charts-row {
    flex-wrap: wrap;
    margin-top: 10px;
  }

  .chart {
    flex-basis: 100% !important;
    margin-bottom: 20px;
  }

  .charts-row:nth-child(2) {
    margin-top: 0;
  }
}

/* 骨架屏加载样式 */
.skeleton-loading .stat-card {
  opacity: 0.6;
  position: relative;
  overflow: hidden;
}

.skeleton-loading .stat-card::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(
          90deg,
          rgba(255, 255, 255, 0) 0%,
          rgba(255, 255, 255, 0.2) 20%,
          rgba(255, 255, 255, 0.5) 60%,
          rgba(255, 255, 255, 0) 100%
  );
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}
</style>